/*
 * 全时云商务服务股份有限公司.
 * Copyright © 2021 京icp备08005473号. All rights reserved.
 * @Date: 2021-08-24.
 * @Author：
 * @Description node 服务
 **/
const http = require('http')
const fs = require('fs')

const wait = (seconds) => {
  return new Promise((resolve) => {
    setTimeout(resolve, seconds * 1000)
  })
}
/**
*@Description
*@Return http 服务创建.
**/
http.createServer(function (request, response) {

  console.log('request come', request.url)

  // etag(entity, [options]) 这个方法为给定的实体产生一个strong etag。这个方法必须获取这个实体的完整内容

  if (request.url === '/script.js') {
    const etag = request.headers['if-none-match']
    if (etag === '777') {
      response.writeHead(304, {
        'Etag': '777',
        'Last-Modified': '123',
        'Content-Type': 'text/javascript',
        'Cache-Control': 'max-age=2000000, no-cache',
      })

      response.end()
    } else {
      response.writeHead(200, {
        'Etag': '777',
        'Last-Modified': '123',
        'Content-Type': 'text/javascript',
        'Cache-Control': 'max-age=2000000, no-cache',
      })

      response.end('console.log("script loaded twice")')
    }
  }

  if (request.url === '/') {
    const html = fs.readFileSync('test.html', 'utf8')  // 以utf-8的编码读取本地test.html文件
    response.writeHead(200, {
      'Content-Type': 'text/html'
    })
    response.end(html)
  }

  if (request.url === '/data') {
    response.writeHead(200, {
      'Vary': 'X-Test-Cache',
      'Cache-Control': 'max-age=2, s-maxage=20, private',
    })
    wait(2).then(() => response.end('监听到 data 接口地址 被访问， 返回success'))
  }

}).listen(8888)

console.log('server listening on 8888')